<template>
  <div id="ddeviceXeomasEdit">
    <Modal v-model="modal.show"  :loading="modal.loading" :title="modal.title"  :mask-closable="false" :footer-hide=true width="700px" :closable="false">
      <Form ref="formGbServer" :model="rowData" label-position="right" :label-width="100" >
        <FormItem :label="$t('gb_server')" >
          <div class="select-input ivu-select ivu-select-single ivu-select-default" style="width: 300px">
            <gbserverselect ref="edtGbServerSelect"
                            v-model="rowData.gbServerId"
                            width="300px"
                            @on-change="gbChange"
                            :readonly="modal.readonly"/>
          </div>
          <Button v-show="!batchAdd && modal.action=='ADD'" @click="changeForm">{{$t('register_more')}}</Button>
          <Button v-show="batchAdd && modal.action=='ADD'" @click="changeForm">{{$t('register_one')}}</Button>
        </FormItem>
        <FormItem>
          <GbCodeRule v-model="codeRule"></GbCodeRule>
        </FormItem>
      </Form>
      <!-- 单个注册  -->
      <Form v-show="!batchAdd" ref="singleValidate" :model="rowData" label-position="right" :label-width="100" :rules="rules1">
        <FormItem :label="$t('code')" >
          <Row :gutter="2">
            <Col span="12"><Input v-model="rowData.codePrefix" :disabled="true" ></Input> </Col>
            <Col span="12"><Input :placeholder="$t('enter_6digits')" v-model="rowData.codeSuffix"  maxlength=6></Input> </Col>
          </Row>
        </FormItem>
        <FormItem :label="$t('manually_modify')" prop="code">
          <Input :placeholder="$t('enter_20digits')" v-model="rowData.code" maxlength=20 />
        </FormItem>
        <FormItem :label="$t('name')" prop="name"><Input v-model="rowData.name" :readonly="modal.readonly"  maxlength=100></Input></FormItem>
        <FormItem :label="$t('video_channel')" prop="defaultChannel"><Input v-model="rowData.defaultChannel" :readonly="modal.readonly" maxlength=20></Input></FormItem>
        <FormItem :label="$t('alarm_channel')"><Input v-model="rowData.defaultAlarmChannel" :readonly="modal.readonly" maxlength=20></Input></FormItem>
        <FormItem :label-width="0">
          <Row :gutter="2">
            <Col span="14">
              <Form :label-width="100">
                <FormItem :label="$t('status')">
                  <RadioGroup v-model="rowData.state">
                    <Radio :label=1 border>{{$t('device_status_1')}}</Radio>
                    <Radio :label=2 border>{{$t('device_status_2')}}</Radio>
                    <Radio :label=3 border>{{$t('device_status_3')}}</Radio>
                  </RadioGroup>
                </FormItem>
              </Form>
            </Col>
            <Col span="10">
              <Form :label-width="100">
                <FormItem :label="$t('subscribe_location')">
                  <i-switch v-model="rowData.subscriberPosition" true-color="#13ce66" false-color="#ff4949" size="large" style="width:70px" :readonly="modal.readonly">
                    <span slot="open">{{$t('subscribe')}}</span>
                    <span slot="close">{{$t('un_subscribe')}}</span>
                  </i-switch>
                </FormItem>
              </Form>
            </Col>
          </Row>
        </FormItem>
      </Form>
      <!-- 批量注册      -->
      <Form v-show="batchAdd" ref="batchValidate" :model="rowData" label-position="right" :label-width="100" >
        <FormItem :label-width="0">
          <Row>
            <Col span="12">
              <Form label-position="right" :label-width="100">
                <FormItem :label="$t('begin_num')">
                  <InputNumber controls-outside v-model="batch.beginNum" :min="1" :max="10000" style="width: 100px;" maxlength=5></InputNumber>
                  <Button @click="getBeginNum">{{$t('get_from_api')}}</Button>
                </FormItem>
                <FormItem :label="$t('from')">
                  <Input controls-outside v-model="batch.beginCode" :disabled="true" style="width:200px" maxlength=5></Input>
                </FormItem>
              </Form>
            </Col>
            <Col span="12">
              <Form label-position="right" :label-width="100">
                <FormItem :label="$t('quantity')">
                  <InputNumber controls-outside v-model="batch.num" :min="1" :max="50" style="width: 100px;" maxlength=2></InputNumber>
                </FormItem>
                <FormItem :label="$t('to')">
                  <Input v-model="batch.endCode" :disabled="true" style="width:200px"></Input>
                </FormItem>
              </Form>
            </Col>
          </Row>
        </FormItem>
      </Form>
      <Form ref="footForm" :model="rowData" label-position="right" :label-width="100">
        <FormItem :label="$t('organization')">
          <OrganizationTree ref="edtOrgSelect"
                            width="200px"
                            v-model="rowData.orgId"
                            :readonly="modal.readonly"
                            prop="orgId"></OrganizationTree>
        </FormItem>
        <FormItem v-show = "!batchAdd" label="$t(personnel)">
          <UserSelect ref="edtUserSelect" v-model="rowData.userId"
                      v-bind:srhValue="rowData.userName"
                      width="200px"
                      :readonly="modal.readonly"> </UserSelect>
        </FormItem>

        <FormItem>
          <div style="float: right;">
            <Button v-show="modal.action!='VIEW'" type="primary"  @click="save" >{{$t('save')}}</Button>
            <Button @click="close">{{$t('cancel')}}</Button>
          </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import OrganizationTree from '@/components/topnav/OrganizationTree';
import gbserverselect from '@/components/topnav/GbServerSelect.vue';
import UserSelect from "_c/topnav/UserModelSelect";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import GbCodeRule from "@/view/GbServer/GbCodeRule";
import {ipValid, portValid} from "_c/validate/FormValidate.js";
//import {addDevice,updateDevice,getBeginCode,batchAddDevice} from '@/api/Device.js';
import Device from '@/api/Device.js';
import CodeRule from "@/api/CodeRule.js";
import {getOne} from '@/api/gbserver.js';
import {apiResult} from "@/libs/util";
export default {
  name:"deviceXeomasEdit",
  components: {gbserverselect,OrganizationTree,UserSelect,Treeselect,GbCodeRule},
  watch: {
    'rowData.gbServerId'(newValue, oldValue) {
      if (!!newValue){
       getOne(JSON.stringify({id:newValue})).then(res => {
         apiResult(res.data,false,result=>{
           this.codeRule.cityId = result.data.cityId;
           this.codeRule.businessId = result.data.businessId;
           this.codeRule.centerTypeId = result.data.centerTypeId;
           this.codeRule.deviceTypeId = result.data.deviceTypeId;
           this.codeRule.netIdentityId = result.data.netIdentityId;

           this.rowData.gbServerCode = result.data.code;
           this.rowData.gbServerName = result.data.name;
           this.rowData.gbServerDomain = result.data.domain;
           this.rowData.cityId = result.data.cityId;
           this.rowData.businessId = result.data.businessId;
           this.rowData.netIdentityId = result.data.netIdentityId;
           this.rowData.deviceTypeId = result.data.deviceTypeId;
           this.rowData.centerTypeId = result.data.centerTypeId;

           this.rowData.codePrefix = result.data.domain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
           this.batch.codePrefix = result.data.domain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
         })
          /*if (res.data.code === 0) {
            this.codeRule.cityId = res.data.data.cityId;
            this.codeRule.businessId = res.data.data.businessId;
            this.codeRule.centerTypeId = res.data.data.centerTypeId;
            this.codeRule.deviceTypeId = res.data.data.deviceTypeId;
            this.codeRule.netIdentityId = res.data.data.netIdentityId;

            this.rowData.gbServerCode = res.data.data.code;
            this.rowData.gbServerName = res.data.data.name;
            this.rowData.gbServerDomain = res.data.data.domain;
            this.rowData.cityId = res.data.data.cityId;
            this.rowData.businessId = res.data.data.businessId;
            this.rowData.netIdentityId = res.data.data.netIdentityId;
            this.rowData.deviceTypeId = res.data.data.deviceTypeId;
            this.rowData.centerTypeId = res.data.data.centerTypeId;

            this.rowData.codePrefix = res.data.data.domain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
            this.batch.codePrefix = res.data.data.domain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
          }else {
            this.$Message.error(res.data.msg)
          }*/
        })
      }
    },
    'rowData.codeSuffix'(newValue, oldValue) {
      if (!!newValue){
        this.rowData.code = this.rowData.codePrefix + this.rowData.codeSuffix;
        this.rowData.defaultChannel = this.rowData.code;
        this.rowData.defaultAlarmChannel = this.rowData.code;
      }
    },
    'codeRule.deviceTypeId'(newValue, oldValue){
      if (!!newValue){
        this.rowData.codePrefix = this.rowData.gbServerDomain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
        this.batch.codePrefix = this.rowData.gbServerDomain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
      }
    },
    'codeRule.netIdentityId'(newValue, oldValue){
      if (!!newValue){
        this.rowData.codePrefix = this.rowData.gbServerDomain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
        this.batch.codePrefix = this.rowData.gbServerDomain + this.codeRule.deviceTypeId + this.codeRule.netIdentityId;
      }
    },
    'batch.beginNum'(newValue, oldValue){
      this.calcBatchCode();
    },
    'batch.num'(newValue, oldValue){
      this.calcBatchCode();
    },
    'batch.codePrefix'(newValue, oldValue){
      this.calcBatchCode();
    },
  },
  computed:{
    rules1() {
      return{code:[{required: true, message: this.$t('code_must_be_enter'), trigger: 'blur'},
          {type:'string',min:20,max:20,message: this.$t('code_must_be_20digits'), trigger: 'blur'}
        ],
        name:[{required: true, message: this.$t('name_must_be_enter'), trigger: 'blur'}],
        defaultChannel:[{required: true, message: this.$t('channel_must_be_enter'), trigger: 'blur'},{type:'string',min:20,max:20,message: '通道号必须是20位数字', trigger: 'blur'}],
        orgId:[{required: true, message: this.$t('organization_must_be_enter'), trigger: 'blur'}]}
    }
  },
  data(){
    return{
      apiDevice: new Device(),
      batchAdd:false,
      api: new CodeRule(),
      batch:{
        beginNum:1,
        num:1,
        beginCode:null,
        endCode:null,
        codePrefix:null,
        gbServerId:null,
        cate:3,
        type:1,
        orgId:null,
      },
      cityTree:{
        placeholder: "行政区划",
        onSelect:function (node, instanceId){},
        onDeselect:function (node, instanceId){}
      },
      codeRule:{
        cityId: null,
        businessId: null,
        centerTypeId: null,
        deviceTypeId: null,
        netIdentityId: null,
      },
      modal:{
        show:false,
        loading:false,
        loading1:false,
        loading2:false,
        readonly:false,
        title:"",
        action:"VIEW",
        callback:null
      },
      rowData: this.initRow(),
      cityCodes:[],
      businessCodes:[],
      centerCodeType:[],
      deviceCodeType:[],
      codeNetIdentity:[],


    }
  },
  methods:{
    //计算开始的结束编号
    calcBatchCode(){
      let codeFix = this.batch.codePrefix;
      if (!!!codeFix){
        if (!!this.rowData.gbServerCode){
          codeFix = this.rowData.gbServerCode.substr(0,14);
        }
      }

      //计算指注册的开始编号和结束编号
      if (!!this.batch.beginNum && !!this.batch.num && !!codeFix){
        let code = this.batch.beginNum.toString();
        while (code.length < 6){
          code = "0" + code;
        }
        this.batch.beginCode = codeFix + code;
        if (this.batch.num == 1){
          this.batch.endCode=this.batch.beginCode;
          return;
        }

        code = (this.batch.beginNum + (this.batch.num - 1)).toString();
        while (code.length < 6){
          code = "0" + code;
        }
        this.batch.endCode = codeFix + code;
      }
    },
    //从后台取起始编号
    getBeginNum(){
      if (!!!this.rowData.gbServerId){
        this.$Message.error(this.$t("server_must_be_enter"));
        return;
      }
      let codeFix = this.batch.codePrefix;
      if (!!!codeFix){
        if (!!this.rowData.gbServerCode){
          codeFix = this.rowData.gbServerCode.substr(0,14);
        }
      }

      this.apiDevice.getBeginCode(codeFix).then(res => {
          apiResult(res.data,false,result=>{
            this.batch.beginNum = result.data;
          })
      })
    },
    changeForm(){
      this.batchAdd = !this.batchAdd;
    },
    initRow:function (){
      return{
        cate:3,
        type:1,
        id:null,
        code:null,
        name:null,
        orgId:null,
        userId:null,
        userName:null,
        defaultChannel:null,
        defaultAlarmChannel:null,
        state:1,
        subscriberPosition:false,
        gbServerId:null,
        gbServerCode:null,
        gbServerName:null,
        gbServerDomain:null,
        cityId:null,
        businessId:null,
        netIdentityId:null,
        deviceTypeId:null,
        centerTypeId:null,
        codePrefix:null,
        codeSuffix:null,
        num:1

      }
    },
    openDialog: function (action,row, callback) {

      this.modal.show=true;
      this.modal.readonly=false;
      this.modal.callback = callback;
      this.modal.show = true;
      this.modal.action = action;
      this.batchAdd = false;
      if (action=="ADD"){
        this.modal.title=this.$t('add');
        this.rowData = this.initRow();
        this.$refs["singleValidate"].resetFields();
      }else if (action=="VIEW"){
        this.modal.title=this.$t('browse');
        this.modal.readonly=true;
      }else if (action=="EDIT"){
        this.modal.title=this.$t('edit');
      }
      if (row != null) {
        this.rowData = row;
      }
      if (action=="VIEW" || action=="EDIT" ){
        this.rowData.codePrefix = this.rowData.code.substr(0,14);
        this.rowData.codeSuffix = this.rowData.code.substr(14,20);
        this.codeRule.cityId = this.rowData.cityId;
        this.codeRule.businessId = this.rowData.businessId;
        this.codeRule.centerTypeId = this.rowData.centerTypeId;
        this.codeRule.deviceTypeId = this.rowData.deviceTypeId;
        this.codeRule.netIdentityId = this.rowData.netIdentityId;
      }else{
        this.codeRule.cityId = null;
        this.codeRule.businessId = null;
        this.codeRule.centerTypeId = null;
        this.codeRule.deviceTypeId = null;
        this.codeRule.netIdentityId = null;

        this.batch.beginNum=1;
        this.batch.num=1;
        this.batch.beginCode=null;
        this.batch.endCode=null;
        this.batch.codePrefix=null;
      }
      console.log(this.rowData);

    },
    save: function(){
      let that = this;
      /** 单个新增 */
      if (!this.batchAdd){
        this.$refs["singleValidate"].validate((valid) => {
          if (that.modal.action == "VIEW"){that.close();}
          if (valid) {
            if (!that.rowData.gbServerId){
              that.$Message.error(this.$t("server_must_be_enter"));
              return;
            }
            if (!that.rowData.code){
              that.$Message.error(code_must_be_enter("code_must_be_enter！"));
              return;
            }
            /** 新增 */
            that.rowData.cate=3;
            if (that.rowData.id == null){
              this.apiDevice.addDevice(JSON.stringify(that.rowData)).then(res => {
                apiResult(res.data,true,result=>{
                  if (!!that.modal.callback) that.modal.callback();
                  that.close();
                });
              })
            }else{
              that.rowData.cate=3;
              this.apiDevice.updateDevice(JSON.stringify(that.rowData)).then(res => {
                apiResult(res.data,true,result=>{
                  if (!!that.modal.callback) that.modal.callback();
                  that.close();
                });
              })
            }
          } else {
            that.$Message.error(this.$t('data_check_error'));
            return;
          }
        })
      }else {
        //批量添加
        if (!!!that.rowData.gbServerId){
          that.$Message.error(this.$t("server_must_be_enter"));
        }
        if (!!!this.codeRule.deviceTypeId){
          that.$Message.error(this.$t("device_type_must_be_enter"));
        }
        if (!!!this.codeRule.netIdentityId){
          that.$Message.error(this.$t("network_identity_must_be_enter"));
        }
        that.batch.gbServerId = that.rowData.gbServerId;
        that.batch.orgId = that.rowData.orgId;
        //console.log(that.rowData.orgId);


        this.apiDevice.batchAddDevice(JSON.stringify(that.batch)).then(res => {
          apiResult(res.data,true,result=>{
            if (!!that.modal.callback) that.modal.callback();
            that.close();
          })
        })
      }

    },
    gbChange: (data)=>{

    },
    close: function(){
      this.modal.show = false;
    }
  },
  mounted() {
    this.api.findCodeCity().then(res=>{
      this.testCity=[];
      apiResult(res.data,false,result=>{
        for(let i in result.data){
          const parent ={
            label:result.data[i].label,
            id:result.data[i].value,
            children:[]
          }
          this.testCity.push(parent);
          if (!! result.data[i].children){
            for(let j in result.data[i].children){
              this.api.genChildren(parent,result.data[i].children[j])
            }
          }
        }
        //console.log(this.testCity);
        this.cityCodes=this.testCity;//res.data.data;
      })
    })

      this.api.findCodeBusiness().then(res=>{
        this.businessCodes=[];
        apiResult(res.data,false,result=>{
          this.businessCodes=result.data;
        })
      })
    this.api.findCodeType().then(res=>{
      this.centerCodeType=[];
      this.deviceCodeType=[];
      apiResult(res.data,false,result=>{
        this.centerCodeType=result.data;
        this.deviceCodeType=this.centerCodeType;
      })
    })

    this.api.findCodeNetIdentity().then(res=>{
      this.codeNetIdentity=[];
      apiResult(res.data,false,result=>{
        this.codeNetIdentity=result.data;
      })
    })

    this.cityTree.placeholder=""
  }

}
</script>
<style lang="less">
@import ".././template";
</style>
